package com.xtianzhuang.www.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.xtianzhuang.www.utils.HttpRequestHolder;

public class VisitInterceptor extends HandlerInterceptorAdapter {
	private static Log logger = LogFactory.getLog(VisitInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub

		long startTime = System.currentTimeMillis();
		HandlerMethod method = (HandlerMethod) handler;

		String methodName = method.getBeanType().getSimpleName() + "." + method.getMethod().getName();
		request.setAttribute("startTime", startTime);
		request.setAttribute("executeMethod", methodName);
		HttpRequestHolder.setRequest(request);
		logger.debug("receive uri " + request.getRequestURL().toString() + "?" + request.getQueryString());
		logger.debug("execute [" + methodName + "]");
		if (isAjax(request)) {
			logger.debug("is ajax input");
		}
		return super.preHandle(request, response, handler);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
		long startTime = (Long) request.getAttribute("startTime");
		String methodName = (String) request.getAttribute("executeMethod");
		long endTime = System.currentTimeMillis();
		long executeTime = endTime - startTime;
		if (isAjax(request)) {
			logger.debug("ajax output");
		}
		logger.info("execute [" + methodName + "]=" + executeTime + "ms");


		super.afterCompletion(request, response, handler, ex);
	}

	/**
	 * 判断ajax请求
	 * @param request
	 * @return
	 */
	private boolean isAjax(HttpServletRequest request) {
		return (request.getHeader("X-Requested-With") != null
				&& "XMLHttpRequest".equals(request.getHeader("X-Requested-With").toString()));
	}
}
